package com.ipay.wechat.factory;

import com.ipay.core.HttpGateway;
import com.ipay.core.Param;
import com.ipay.utils.*;
import com.ipay.wechat.component.Wechat;
import com.ipay.wechat.pojo.*;
import com.ipay.wechat.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("orderStatusTask")
public class OrderStatusTask {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private TradeRecordService tradeRecordService;
    @Autowired
    private PayChannelService payChannelService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private HttpGateway gateway;
    @Autowired
    private Wechat wechat;

    public void queryRefundStart() {
        //查询退款订单 支付状态为【5退款处理中】 类型【退款】
        Map<String, Object> maptr = new HashMap<String, Object>();
        maptr.put("category", Constant.CATEGORY_TK);
        maptr.put("status", Constant.STATUS_PROCESSING);
        List<TradeRecord> tradeRecordList = tradeRecordService.findTkTradeRecordList(maptr);
        logger.info("=======queryRefundStart(查询退款订单)==========:" + tradeRecordList.size());
        for (TradeRecord tradeRecord : tradeRecordList) {
            try {
                // 退款订单信息
                if (tradeRecord == null || StringUtil.isEmpty(tradeRecord.getBusId()) || StringUtil.isEmpty(tradeRecord.getResource())) {
                    return;
                }
                if (Constant.STATUS_YZF.equals(tradeRecord.getStatus())) {
                    return;
                }
                ///查询下商户收款参数信息
                Map<String, Object> mapPayChannel = new HashMap<String, Object>();
                mapPayChannel.put("merchantNo", tradeRecord.getBusId());
                mapPayChannel.put("payState", Constant.Status.ENABLE.getValue());//状态 0、删除 1、启用 2、禁用
                if (tradeRecord.getResource() != null && Constant.Resource.RESOURCE_WX.getValue().equals(tradeRecord.getResource())) {//获取：来源（0 微信、1 支付宝）
                    mapPayChannel.put("payType", Constant.PayType.PAY_WX.getValue());//微信
                } else if (tradeRecord.getResource() != null && Constant.Resource.RESOURCE_ZFB.getValue().equals(tradeRecord.getResource())) {
                    mapPayChannel.put("payType", Constant.PayType.PAY_ZFB.getValue());//支付宝
                }else{
                    return;
                }
                PayChannelEntity payChannel = payChannelService.queryPayBymerchantNo(mapPayChannel);
                if (payChannel == null || StringUtil.isEmpty(payChannel.getPayChannelNo()) || StringUtil.isEmpty(payChannel.getPayKey())) {
                    return;
                }

                Map<String, String> map = new HashMap<String, String>();
                map.put("service", "unified.trade.refundquery");
                map.put("version", "2.0");
                map.put("charset", "UTF-8");
                map.put("sign_type", "MD5");
                map.put("mch_id", payChannel.getPayChannelNo());
                //商户订单号  -TODO 与 威富通订单号必须有一个存在
                map.put("refund_id", tradeRecord.getRefundId());//平台退款单号
                map.put("out_refund_no", tradeRecord.getRecordNo());//商户退款单号
                //威富通订单号
                map.put("transaction_id", tradeRecord.getOrderId().toString());//平台订单号
                map.put("out_trade_no", tradeRecord.getOrderId().toString());//商户订单号
                map.put("nonce_str", RandomStringUtils.getRandomStringByLength(32));
                map.put("refund_channel", "ORIGINAL");
                String strtosign = MapUtils.formatUrlMap(map, false, false);
                String signstr = MD5.sign(strtosign, "&key=" + payChannel.getPayKey(), "utf-8");
                map.put("sign", signstr);
                Param param = Param.create();
                param.putAll(map);
                // 退款接口
                gateway.url = "https://pay.swiftpass.cn/pay/gateway";
                Param resultparam = gateway.post(param);
                System.out.println(resultparam.toString());
                String status = resultparam.get("status");
                String msg = "";
                if (status.equals("0")) { // 成功
                    String result_code = resultparam.get("result_code");// 业务成功结果
                    if (result_code.equals("0")) {
                        String refund_count = resultparam.get("refund_count");//退款记录数
                        //Integer.parseInt
                        Object refimdCountObj = StringUtil.isNotEmptyValue(refund_count, 0);
                        int refundCount = Integer.parseInt(String.valueOf(refimdCountObj));
                        for (int i = 0; i < refundCount; i++) {
                            TradeRecord payorder = new TradeRecord();
                            String outRefundNo = resultparam.get("out_refund_no_" + i);//商户退款单号
                            String refundId = resultparam.get("refund_id_" + i);//平台退款单号
                            payorder.setRefundTime(resultparam.get("refund_time_" + i));//退款时间
                            payorder.setRecordNo(outRefundNo);
                            payorder.setRefundId(refundId);
                            String refundStatus = resultparam.get("refund_status_" + i);//退款状态
                            if ("SUCCESS".equals(refundStatus)) {
                                msg = "退款成功";
                                payorder.setStatus(Constant.STATUS_YTK);// 已退款
                            } else if ("FAIL".equals(refundStatus)) {
                                msg = "退款失败";
                                payorder.setStatus(Constant.STATUS_TKSB);
                            } else if ("PROCESSING".equals(refundStatus)) {
                                msg = "退款处理中";
                                payorder.setStatus(Constant.STATUS_PROCESSING);
                            } else if ("NOTSURE".equals(refundStatus)) {
                                msg = "未确定， 需要商户原退款单号重新发起";
                                payorder.setStatus(Constant.STATUS_NOTSURE);
                            } else if ("CHANGE".equals(refundStatus)) {
                                msg = "转入代发，退款到银行发现用户的卡作废或者冻结了，导致原路退款银行卡失败，资金回流到商户的现金帐号，需要商户人工干预，通过线下或者平台转账的方式进行退款.";
                                payorder.setStatus(Constant.STATUS_CHANGE);
                            }
                            payorder.setRemark(msg);
                            tradeRecordService.updateRefundStart(payorder);

                            if (Constant.STATUS_YTK.equals(payorder.getStatus())) {
                                //微信信息推送
                                String sendType = String.valueOf(Constant.SendType.SEND_REFUND.getValue());
                                pushMessage(tradeRecord.getBusId(),tradeRecord.getCodeNo(), tradeRecord.getAmount().toString(), tradeRecord.getResource(), tradeRecord.getRecordNo(), tradeRecord.getOrderdate(), sendType);
                            }
                        }
                    } else {
                        msg = resultparam.get("err_msg");//
                    }
                }
            }catch (Exception e){
                logger.error("退款订单检索状态异常",e);
            }
        }
    }


    /**
     * 支付订单状态查询
     */
    public void tradequeryStart() {
        Map<String, Object> maptr = new HashMap<String, Object>();
        maptr.put("category", Constant.CATEGORY_ZF);//类型（0 支付 1 退款）
        maptr.put("status", Constant.STATUS_PROCESSING);//退款/收款失败；
        maptr.put("pay_result", Constant.STATUS_WZ);//退款/收款失败；
        List<TradeRecord> tradeRecordList = tradeRecordService.findTkTradeRecordList(maptr);
        logger.info("======支付订单状态查询==定时器===========:" + tradeRecordList.size());
        for (TradeRecord tradeRecord : tradeRecordList) {
            try {
                // 退款订单信息
                if (tradeRecord == null || StringUtil.isEmpty(tradeRecord.getBusId()) || StringUtil.isEmpty(tradeRecord.getResource())) {
                    return;
                }
                if (Constant.STATUS_YZF.equals(tradeRecord.getStatus())) {
                    return;
                }
                ///查询下商户收款参数信息
                Map<String, Object> mapPayChannel = new HashMap<String, Object>();
                mapPayChannel.put("merchantNo", tradeRecord.getBusId());
                mapPayChannel.put("payState", Constant.Status.ENABLE.getValue());//状态 0、删除 1、启用 2、禁用
                if (tradeRecord.getResource() != null && Constant.Resource.RESOURCE_WX.getValue().equals(tradeRecord.getResource())) {//获取：来源（0 微信、1 支付宝）
                    mapPayChannel.put("payType", Constant.PayType.PAY_WX.getValue());//微信
                } else if (tradeRecord.getResource() != null && Constant.Resource.RESOURCE_ZFB.getValue().equals(tradeRecord.getResource())) {
                    mapPayChannel.put("payType", Constant.PayType.PAY_ZFB.getValue());//支付宝
                }else{
                    return;
                }
                PayChannelEntity payChannel = payChannelService.queryPayBymerchantNo(mapPayChannel);
                if (payChannel == null || StringUtil.isEmpty(payChannel.getPayChannelNo()) || StringUtil.isEmpty(payChannel.getPayKey())) {
                    return;
                }

                Map<String, String> map = new HashMap<String, String>();
                map.put("service", "unified.trade.query");
                map.put("version", "2.0");
                map.put("charset", "UTF-8");
                map.put("sign_type", "MD5");
                map.put("mch_id", payChannel.getPayChannelNo());
                map.put("transaction_id", "");//平台订单号
                map.put("out_trade_no", tradeRecord.getRecordNo().toString());//商户订单号
                map.put("nonce_str", RandomStringUtils.getRandomStringByLength(32));
                String strtosign = MapUtils.formatUrlMap(map, false, false);
                String signstr = MD5.sign(strtosign, "&key=" + payChannel.getPayKey(), "utf-8");
                map.put("sign", signstr);
                Param param = Param.create();
                param.putAll(map);
                gateway.url = "https://pay.swiftpass.cn/pay/gateway";
                Param resultparam = gateway.post(param);
                logger.info("==================" + resultparam);
                String status = resultparam.get("status");
                if (status.equals("0")) { // 成功
                    String result_code = resultparam.get("result_code");// 业务成功结果
                    if (result_code.equals("0")) {
                        // SUCCESS—支付成功 REFUND—转入退款 NOTPAY—未支付 CLOSED—已关闭 REVERSE—已冲正 REVOK—已撤销
                        String trade_state = resultparam.get("trade_state");
                        if (trade_state.equals("SUCCESS")) {
                            String transaction_id = resultparam.get("transaction_id");//平台订单号
                            String time_end = resultparam.get("time_end");//支付完成时间
                            String bank_type = resultparam.get("bank_type");//付款银行
                            String openid = resultparam.get("openid");//用户标识
                            tradeRecord.setStatus(Constant.STATUS_YZF.toString());
                            tradeRecord.setPayResult(Constant.PAY_RESULT_SUCCESS);//支付结果：0—成功；其它—失败
                            tradeRecord.setTransactionId(transaction_id);
                            tradeRecord.setTimeEnd(time_end);
                            tradeRecord.setBankType(bank_type);
                            tradeRecord.setOpenid(openid);
                        } else if (trade_state.equals("REFUND")) { //转入退款
                            tradeRecord.setStatus(Constant.STATUS_REFUND.toString());
                            tradeRecord.setPayResult(Constant.PAY_RESULT_SUCCESS);//支付结果：0—成功；其它—失败
                        } else if (trade_state.equals("NOTPAY")) { //未支付
                            tradeRecord.setStatus(Constant.STATUS_NOTPAY.toString());
                            tradeRecord.setPayResult(Constant.PAY_RESULT_ERROR);//支付结果：0—成功；其它—失败
                        } else if (trade_state.equals("CLOSED")) { //已关闭
                            tradeRecord.setStatus(Constant.STATUS_YGB.toString());
                            tradeRecord.setPayResult(Constant.PAY_RESULT_ERROR);//支付结果：0—成功；其它—失败
                        } else if (trade_state.equals("REVERSE")) { //已冲正
                            tradeRecord.setStatus(Constant.STATUS_REVERSE.toString());
                            tradeRecord.setPayResult(Constant.PAY_RESULT_ERROR);//支付结果：0—成功；其它—失败
                        } else if (trade_state.equals("REVOK")) { //已撤销
                            tradeRecord.setStatus(Constant.STATUS_REVOK.toString());
                            tradeRecord.setPayResult(Constant.PAY_RESULT_ERROR);//支付结果：0—成功；其它—失败
                        }
                        TPayresultEntity entity = initPayResultNotify(resultparam);
                        tradeRecordService.updateRefundStart(tradeRecord, entity);
                        if (Constant.STATUS_YZF.equals(tradeRecord.getStatus())) {
                            //微信信息推送
                            String sendType = String.valueOf(Constant.SendType.SEND_RECEIVABLES.getValue());
                            pushMessage(tradeRecord.getBusId(),tradeRecord.getCodeNo(),tradeRecord.getAmount().toString(),tradeRecord.getResource(),tradeRecord.getRecordNo(),tradeRecord.getOrderdate(),sendType);
                        }
                    } else {
                        logger.info("=============err_code" + resultparam.get("err_code") + "  =   err_msg:" + resultparam.get("err_msg"));
                    }
                } else {
                    logger.info("=================" + tradeRecord.getOrderId().toString() + "  =  message:" + resultparam.get("message"));
                }
            }catch (Exception e){
                logger.error("收款订单检索状态异常",e);
            }
        }
    }

    /**
     * 微信信息推送处理
     *
     * @param merchantId //商户编号
     * @param amount     //金额
     * @param resource   //获取：来源（0 微信、1 支付宝）
     * @param recordno   //订单号
     * @param orderdate  //订单创建时间
     */
    private void pushMessage(String merchantId,String codeNo, String amount, String resource, String recordno, Date orderdate,String sendType) {
        logger.info("============进入信息推送===============" + merchantId +"  =  "+codeNo+ " - " + amount + " - " + resource + " - " + recordno + " - " + orderdate);
        List<WechatLogin> loginList = loginService.findWechatLoginByMerchantId(merchantId,codeNo);
        for (WechatLogin wechatLogin : loginList) {
            if (wechatLogin != null && StringUtil.isNotEmpty(wechatLogin.getOpenid()) //getOpenid微信openid；
                    && StringUtil.isNotEmpty(wechatLogin.getIsNotify())  //getIsNotify是否通知 0:表示不通知 、1:表示通知
                    && StringUtil.isNotEmpty(wechatLogin.getStatus())) {  //getStatus 状态：0未登陆，1已登录
                if (Constant.ISNOTIFY_TZ.intValue() == wechatLogin.getIsNotify() //是否通知 0:表示不通知 、1:表示通知
                        && Constant.LOGIN_STATUS_YDL.intValue() == wechatLogin.getStatus()) { ///状态：0未登陆，1已登录
                    Map<String, Object> mapMessage = new HashMap<String, Object>();
                    mapMessage.put("openid", wechatLogin.getOpenid());
                    mapMessage.put("sendType", sendType);//发送退款通知
                    mapMessage.put("keyword1", amount);//金额
                    mapMessage.put("keyword2", wechatLogin.getShopname());//商家名称
                    mapMessage.put("keyword3", resource);//支付方式  1微信，2支付宝，3qq钱包
                    mapMessage.put("keyword4", recordno);//交易单号
                    String orderDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orderdate);
                    mapMessage.put("keyword5", orderDate);//交易时间
                    mapMessage.put("url", wechat.getBaseUrl() + "menu/?action=tradingCenter");//Constant.DOMAINURL_HTTPS
                    tradeRecordService.pushTradeMessage(mapMessage);
                }
            }
        }
    }

    /**
     * 支付通知结果  存表
     * @param map
     */
    public TPayresultEntity initPayResultNotify(Param map) {
        /*{appid=wx0781c1dea664cd9a, charset=UTF-8, mch_id=101590141241, nonce_str=btlyz62fb6bz7oy5v3rx8gv1gffecx4c,
                result_code=0, sign=7BD728B9A34F87797AA7880AD51D246F,
                sign_type=MD5, status=0, trade_state=NOTPAY,
                trade_state_desc=订单未支付, version=2.0}

        {appid=wx0781c1dea664cd9a, bank_type=CFT, charset=UTF-8, fee_type=CNY, is_subscribe=N,
                mch_id=101590141241, nonce_str=znw5nf3qet2gxvx86jy7xlvgsxw04xeo, openid=o-Rj7wDLTU5bYAnKm-3o7fDgJzIc,
                out_trade_no=D2017103109000000247, out_transaction_id=4200000028201710311414571616,
                result_code=0, sign=453178C0F8B279F2A8C21D15055ADCB1, sign_type=MD5, status=0,
                sub_appid=wxf7fca97aabff09c9, sub_is_subscribe=Y, sub_openid=oejR50ugUxEvsvfyzR5dHfZv_8Mk,
                time_end=20171031092614, total_fee=1, trade_state=SUCCESS, trade_type=pay.weixin.jspay,
                transaction_id=101590141241201710314154597763, version=2.0}*/
        TPayresultEntity entity = new TPayresultEntity();
        entity.setOpenid(StringUtil.isNotEmptyValue(map.get("openid"), "").toString());//用户标识
        entity.setTradeType(StringUtil.isNotEmptyValue(map.get("trade_type"), "").toString());//交易类型
        entity.setIsSubscribe(StringUtil.isNotEmptyValue(map.get("is_subscribe"), "").toString());//是否关注公众账号
        entity.setPayResult(StringUtil.isNotEmptyValue(map.get("pay_result"), "").toString());
        //支付结果信息，支付成功时为空
        entity.setPayInfo(StringUtil.isNotEmptyValue(map.get("pay_info"), "").toString());
        entity.setTransactionId(StringUtil.isNotEmptyValue(map.get("transaction_id"), "").toString());//商户订单号
        entity.setOutTransactionId(StringUtil.isNotEmptyValue(map.get("out_transaction_id"), "").toString());//第三方订单号
        entity.setSubIsSubscribe(StringUtil.isNotEmptyValue(map.get("sub_is_subscribe"), "").toString());
        entity.setSubAppid(StringUtil.isNotEmptyValue(map.get("sub_appid"), "").toString());
        entity.setSubOpenid(StringUtil.isNotEmptyValue(map.get("sub_openid"), "").toString());
        entity.setOutTradeNo(StringUtil.isNotEmptyValue(map.get("out_trade_no"), "").toString());//商户订单号
        entity.setTotalFee(Integer.valueOf(StringUtil.isNotEmptyValue(map.get("total_fee"), 0).toString()));//总金额
        //现金券支付金额<=订单总金额， 订单总金额-现金券金额为现金支付金额
        entity.setCouponFee(Integer.valueOf(StringUtil.isNotEmptyValue(map.get("coupon_fee"), 0).toString()));//现金券金额
        entity.setFeeType(StringUtil.isNotEmptyValue(map.get("fee_type"), "").toString());//货币种类
        //商家数据包，原样返回
        entity.setAttach(StringUtil.isNotEmptyValue(map.get("attach"), "").toString());//附加信息
        entity.setBankType(StringUtil.isNotEmptyValue(map.get("bank_type"), "").toString());//付款银行
        //银行订单号，若为微信支付则为空
        entity.setBankBillno(StringUtil.isNotEmptyValue(map.get("bank_billno"), "").toString());//银行订单号
        entity.setTimeEnd(StringUtil.isNotEmptyValue(map.get("time_end"), "").toString());//支付完成时间
        return entity;
    }
}
